//
//  GoodsDetailViewController.swift
//  Box
//
//  Created by mn on 2025/4/2.
//

import UIKit
import Kingfisher

enum GoodsDetailCellType {
    case text
    case info(info: GoodsModel)
    case image(url: String)
}

class GoodsDetailViewController: BaseViewController{
    let id: String
    var details = [GoodsDetailCellType]()
    init(id: String) {
        self.id = id
        super.init(nibName: nil, bundle: nil)
    }
    
    @MainActor required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        self.title = "商品详情"
        view.addSubview(tableView)
 
        tableView.bounces = false
        tableView.dataSource = self
        tableView.delegate = self
        tableView.separatorColor = .clear
        tableView.backgroundColor = .fromHex("#F4F6F8")
        tableView.contentInsetAdjustmentBehavior = .never
        tableView.registerCells([GoodsImageCell.self,
                                 GoodsInfoCell.self,
                                 GoodsTextCell.self])
        
        view.addSubview(button)
        button.snp.makeConstraints { make in
            make.left.right.equalToSuperview().inset(46.5)
            make.bottom.equalTo(view.safeAreaLayoutGuide.snp.bottom).offset(-24)
            make.height.equalTo(52)
        }
        tableView.snp.makeConstraints { make in
            make.top.equalTo(nav.snp.bottom)
            make.left.right.equalToSuperview()
            make.bottom.equalTo(button.snp.top)
        }
        getGoodsDetail()
    }
    var goodsModel: GoodsModel?
    func getGoodsDetail() {
        APIService.request(api: .getGoodsDetail(goodsId: id)) {
            [weak self] (result,response) in
            guard let self else { return }
            if result.success, let detail: GoodsModelDetailData = Decoder.data(response) {
                goodsModel = detail.data
                details.append(.image(url: detail.data.imgUrlList.first ?? ""))
                details.append(.info(info: detail.data))
                details.append(.text)
                detail.data.imgDetailUrlList.forEach { url in
                    self.details.append(.image(url: url))
                }

                tableView.reloadData()
            }
        }
    }
    
    private let tableView = UITableView()
    lazy var button: InsetBorderButton = {
        let button = InsetBorderButton(type: .custom)
        button.setTitle("立即购买", for: .normal)
        button.setTitleColor(.fromHex("#CAFE67"), for: .normal)
        button.layer.cornerRadius = 7.5
        button.titleLabel?.font = .systemFont(ofSize: 16)
        button.backgroundColor = .black
        button.borderColor = .white
        button.addAction {
            [weak self] in
            if !UserManager.shared.isLogin() {
                UserManager.shared.pushToLogin(self)
                return
            }
            
            let vc = CreateOrderViewController()
            vc.goodsModel = self?.goodsModel
            vc.modalPresentationStyle = .overFullScreen
            self?.present(vc, animated: false)
        }
        return button
    }()
    
}
extension GoodsDetailViewController : UITableViewDataSource,UITableViewDelegate {
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        details.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        switch details[indexPath.row] {
        case .image(let url):
            let cell: GoodsImageCell = tableView.cell(indexPath)
            cell.setImage(url: url)
            cell.imageLoadedCallback = { [weak tableView] in
                // 图片加载完后触发刷新布局
                tableView?.beginUpdates()
                tableView?.endUpdates()
            }
            return cell
        case .info(let info):
            let cell: GoodsInfoCell = tableView.cell(indexPath)
            cell.titleLabel.text = info.name
            cell.specificationCountLabel.text = "\(info.count)"
            cell.priceLabel.text = String(format: "%.2f元", Float(info.recyclePrice ?? 0) * 0.01)
            return cell
        case .text:
            let cell: GoodsTextCell = tableView.cell(indexPath)
            cell.titleLabel.text = "详情介绍"
            return cell

        }
        
    }
    
}

